package com.ljc.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ljc.constant.RabbitMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * 向mq发送消息，并进行保证消息可靠性处理
 */
@Component
@Slf4j
public class DanmuRabbitMQUtils {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public void sendDanmuAsync(JSONObject jsonObject) {
        // 将 headers 添加到 MessageProperties 中，并发送消息
        String messageId = UUID.randomUUID().toString();
        String json = new Gson().toJson(jsonObject);
        // 将消息投递到MQ，并设置消息的一些参数
        rabbitTemplate.convertAndSend(RabbitMQConstant.DANMU_EXCHANGE_NAME,
                RabbitMQConstant.DANMU_EXCHANGE_ROUTING_KEY, json, message -> {
                    MessageProperties messageProperties = message.getMessageProperties();
                    //生成全局唯一id
                    messageProperties.setMessageId(messageId);
                    messageProperties.setContentEncoding("utf-8");
                    return message;
                });
    }
}
